package cn.kgc.vue.shiro;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @author 课工场
 * @date 2024/6/28
 * @description   shiro 环境的配置类
 */
@Configuration
public class SpringbootShiroWebConfig {

    //  ShiroFilterFactoryBean   将shiro中的过滤器添加到spring容器
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        // 添加自定义的filter  到shiroFilter
        HashMap<String, Filter> filterHashMap = new HashMap<>();
        filterHashMap.put("customer",new WebTokenFilter());
        shiroFilterFactoryBean.setFilters(filterHashMap);

        // 定义拦截规则
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("/user/captcha","anon");
        linkedHashMap.put("/user/login","anon");
        linkedHashMap.put("/user/unAuth","anon");

        // 放行swagger相关静态资源
        linkedHashMap.put("/doc.html","anon");
        linkedHashMap.put("/swagger-resources", "anon");
        linkedHashMap.put("/favicon.ico", "anon");
        linkedHashMap.put("/v2/api-docs", "anon");
        linkedHashMap.put("/webjars/css/app.b2512131.css", "anon");
        linkedHashMap.put("/webjars/js/chunk-vendors.9ff0f717.js", "anon");
        linkedHashMap.put("/webjars/js/app.ed549958.js", "anon");


        // 使用自定义的过滤器实现请求的拦截
        linkedHashMap.put("/**","customer");

        shiroFilterFactoryBean.setLoginUrl("/user/unAuth");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(linkedHashMap);
        return shiroFilterFactoryBean;
    }

    //defaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }


    @Bean
    public CustomerRealm customerRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;
    }

}
